import { reactive, ref } from 'vue'

// 修改函数参数，支持options配置对象
export function useInfiniteLoad(
  apiFn: Function, 
  options: { 
    initialParams?: Record<string, any>,
    transformResponse?: (response: any) => any[]  // 添加转换函数类型定义
  } = {}
) {
  const { initialParams = {}, transformResponse } = options;
  
  const params = reactive({
    page: 1,
    pageSize: 10,
    ...initialParams  // 使用options中的initialParams
  })
  
  const list = ref<Recordable[]>([])
  const isLoading = ref(false)
  const hasMore = ref(true)

  const loadMore = async () => {
    if (isLoading.value || !hasMore.value) return
    isLoading.value = true
    try {
      const res: any = await apiFn(params)
      
      // 应用响应转换函数，默认返回res.list
      const currentList = transformResponse 
        ? transformResponse(res) 
        : (res.list || []);
      
      if (params.page === 1) {
        list.value = currentList
      } else {
        list.value = [...list.value, ...currentList]
      }
      
      // 判断是否还有更多数据
      hasMore.value = currentList.length >= params.pageSize
      if (hasMore.value) {
        params.page++
      }
    } finally {
      isLoading.value = false
    }
  }

  const reset = () => {
    params.page = 1
    hasMore.value = true
    list.value = []
  }

  return {
    list,
    isLoading,
    hasMore,
    loadMore,
    reset,
    params
  }
}